package com.saicmotor.hk2.controller;

import com.saicmotor.hk2.model.User;
import com.saicmotor.hk2.service.CommonService;
import com.saicmotor.hk2.service.UserRoleService;
import com.saicmotor.hk2.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.logging.Logger;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    CommonService commonService;
    @Autowired
    UserRoleService userRoleService;

    @RequestMapping(value = "/age",params = "name")
    public String getAgeOfUser(String name) {   //http://localhost:8080/user/age?name=setName
        try {
            return String.valueOf(userService.getAgeByName(name));
        } catch (Exception e) {
            log.error("异常地点：hk2.service.userService.getAgeByName(name)", e);
            return "DATA DO NOT EXIST";
        }
    }


    @RequestMapping(value = "/name",params = "age")
    public List<String>getNameByAge(int age){
        return userService.getNameByAge(age);
    }

    @RequestMapping(value = "/all")
    public List<User> getAll() {
        return userService.getAll();
    }

    @RequestMapping("/add")
    public String insertInfoOfUser(String name,int age) { //http://localhost:8080/user/info?name=setName&age=setAge
        if (commonService.checkName("user", name)) {
            return name + " is EXISTS";
        } else {
            userService.insertUserInfo(name, age);
            return "Insert [" + name + "] Complete";
        }
    }

    @RequestMapping(value = "/delete",params = "name")
    public String deleteUser(String name) {
        userService.deleteByName(name);
        userRoleService.deleteByUserName(name);
        return "Delete [" + name + "] Complete";
    }

    @RequestMapping(value = "/delete",params = "age")
    public String deleteUser(int age) {
        userService.deleteByAge(age);
        return "Delete Age of [" + age + "] Complete";
    }

    @RequestMapping("/update")
    public String updateAgeOfUser(String name,int age){
        if (!commonService.checkName("user", name)) {
            return name + " is NOT EXIST";
        } else {
            userService.updateAgeByName(name, age);
            return "Update [" + name + "] Complete";
        }
    }

    @RequestMapping("/create")
    public String UserTableCreation(){
        if (commonService.checkTable("user")) {
            return "\"user\" Table Exists";
        } else {
            userService.createUserTable("user");
            return "Create \"user\" Table Complete";
        }
    }

}
